package day_6_30;

public class Main2 {
    /**
     * 92. 反转链表 II
     * https://leetcode.cn/problems/reverse-linked-list-ii/description/
     */
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode(0);
        newHead.next = head;

        right -= left;
        ListNode cur = newHead;
        while(left-- > 1) {
            cur = cur.next;
        }

        ListNode a = cur.next;
        ListNode b = cur.next.next;
        while(right-- > 0) {
            ListNode next = b.next;
            b.next = a;
            a = b;
            b = next;
        }

        cur.next.next = b;
        cur.next = a;

        return newHead.next;
    }
}
